package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.woyao.core.model.Area;
import com.woyao.core.model.AreaResponse;
import com.woyao.core.model.Demand;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.service.AreaService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;

public class FilterLocation extends AppCompatActivity {

    TextView locationtitle = null;
    HashMap<String,String> parents = new HashMap<String,String>() ;

    private  String curlocation = "";

    private RecyclerView chosenList = null;
    private NewFilterAapter chosenAdapter;

    private RecyclerView alllist = null;
    private SingleTreeAdapter allAdapter;

    private Demand demand;
    boolean changed = false;
    ProgressDialog progressDialog;
    private String from = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_filter_location);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
        this.setTitle("选择合作地区");

        chosenList = (RecyclerView) findViewById(R.id.recyclerLocation);
        LinearLayoutManager chosenLayoutManager = new LinearLayoutManager(this);
        chosenLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        chosenList.setLayoutManager(chosenLayoutManager);


        alllist = (RecyclerView) findViewById(R.id.id_location_list);
        LinearLayoutManager allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        TextView roottitle = (TextView) findViewById(R.id.roottitle);
        roottitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                curlocation ="";
                locationtitle.setText(  "" );
                loadAllData();
            }
        });

        locationtitle = (TextView) findViewById(R.id.alltitle);

        Button finishbtn = (Button) findViewById(R.id.finishlocation);

        finishbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.putExtra("changed", changed );
                intent.putExtra("result",chosenAdapter.getSelectionKeyValue() );
                setResult(666, intent);
                finish();
            }
        });

        Button gobackbtn = (Button) findViewById(R.id.goback);

        gobackbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (parents.get(curlocation ) != null) {
                    curlocation = parents.get(curlocation ) ;
                    locationtitle.setText(  "" );
                    loadAllData();
                }
            }
        });


        Intent intent = getIntent();

        KeyValueList include = (KeyValueList)intent.getExtras().get("include");

        chosenAdapter = new NewFilterAapter(this, include.getContent() ,include.getContent());

        chosenAdapter.setChangedHandler( new NewFilterAapter.Changed(){
            @Override
            public void dataChanged() {
                changed = true;
            }
        });

        this.chosenList.setAdapter(chosenAdapter);

        loadAllData();
        

    }


    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(0, intent);
        finish();
        return true;
    }




    private void loadAllData(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void,Void,AreaResponse> task =
                new AsyncTask<Void, Void, AreaResponse>() {
                    @Override
                    protected AreaResponse doInBackground(Void... params) {
                        AreaService svc = ServiceFactory.get(AreaService.class);
                        Call<AreaResponse> responseCall = svc.getArea(curlocation,WoyaoooApplication.userId,"no","filter");
                        AreaResponse response = null ;
                        try {
                            response = responseCall.execute().body();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return response;
                    }
                    @Override
                    protected void onPostExecute(final AreaResponse response) {
                        renderAll(response.getContent());
                        progressDialog.dismiss();
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }

    private void renderAll(ArrayList<Area> arealist){

        ArrayList<Map<String,String>> mapList = new ArrayList<>();

        for(Area ar : arealist){
            HashMap<String,String> map = new HashMap<>();
            map.put("no", ar.getId() +"");
            map.put("name", ar.getName());
            map.put("description",ar.getDescription());
            map.put("choose","true");
            map.put("childs", ar.getChilds() +"");
            mapList.add(map);
        }
        allAdapter = new SingleTreeAdapter(this,  mapList );

        allAdapter.setChangedHandler(new SingleTreeAdapter.Changed() {
            @Override
            public void itemSelected(Map<String, String> one) {
                if (chosenAdapter.getSelectionKeyValue().getContent().size() >= 10) {
                    Common.showSnack( FilterLocation.this, alllist, "最多选择10个" ) ;
                }else{
                    chosenAdapter.AddNewOne(one);
                    chosenAdapter.notifyDataSetChanged();
                    changed = true;
                }
//                Common.showSnack( FilterLocation.this, alllist, "选择了"+one.get("name") ) ;

            }

            @Override
            public void itemGetChildren(Map<String, String> one) {
                parents.put(one.get("no"), curlocation );
                curlocation = one.get("no");
                locationtitle.setText(  one.get("name") );
                loadAllData();

            }
        });
        alllist.setAdapter(allAdapter);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}

